<template>
  <div class="online-availability-container">
    <h4>设置线上可预约时间</h4>

    <!-- 基础配置区域 -->
    <el-card class="config-card" shadow="hover">
      <div class="section-title">基础时间段管理</div>
      <div class="time-slot-section">
        <el-button type="primary" @click="showAddTimeSlotDialog">添加时间段</el-button>
        <el-table :data="timeSlotList" border style="margin-top: 15px" v-loading="loadingTimeSlots">
          <el-table-column prop="slotId" label="ID" width="80" />
          <el-table-column prop="dayOfWeek" label="星期" width="120">
            <template #default="scope">
              {{ translateDayOfWeek(scope.row.dayOfWeek) }}
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="120" />
          <el-table-column prop="endTime" label="结束时间" width="120" />
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button type="danger" size="small" @click="handleDeleteTimeSlot(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 周发布区域 -->
    <el-card class="publish-card" shadow="hover" style="margin-top: 20px">
      <div class="section-title">线上评估周发布</div>
      <div class="week-info">
        <span>当前周次: {{ currentWeekInfo }}</span>
        <el-date-picker
          v-model="publishDate"
          type="date"
          placeholder="选择发布日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </div>

      <div class="slots-config">
        <div v-if="selectedSlotIds.length === 0" class="empty-configs">
          <el-empty description="暂无已选择时间段" :image-size="80"></el-empty>
        </div>
        <el-table v-else :data="selectedSlotsInfo" border style="margin-top: 15px">
          <el-table-column label="星期" width="100">
            <template #default="scope">
              {{ translateDayOfWeek(scope.row.dayOfWeek) }}
            </template>
          </el-table-column>
          <el-table-column label="开始时间" width="120" prop="startTime" />
          <el-table-column label="结束时间" width="120" prop="endTime" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeSelectedSlot(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="add-config-section">
        <el-form :inline="true" class="add-config-form">
          <el-form-item label="时间段">
            <el-select v-model="selectedSlotId" placeholder="选择时间段" class="status-select">
              <el-option
                v-for="slot in availableSlots"
                :key="slot.slotId"
                :label="`${translateDayOfWeek(slot.dayOfWeek)} ${slot.startTime}-${slot.endTime}`"
                :value="slot.slotId"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addSelectedSlot">添加时间段</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="publish-section">
        <el-button type="success" @click="publishOnlineConfig" :loading="publishing">
          发布本周线上评估时间
        </el-button>
      </div>
    </el-card>

    <!-- 添加时间段对话框 -->
    <el-dialog v-model="timeSlotDialogVisible" title="添加时间段" width="500px">
      <el-form :model="timeSlotForm" label-width="100px" ref="timeSlotFormRef">
        <el-form-item
          label="星期"
          prop="dayOfWeek"
          :rules="{ required: true, message: '请选择星期' }"
        >
          <el-select v-model="timeSlotForm.dayOfWeek" placeholder="选择星期">
            <el-option label="星期一" value="Monday" />
            <el-option label="星期二" value="Tuesday" />
            <el-option label="星期三" value="Wednesday" />
            <el-option label="星期四" value="Thursday" />
            <el-option label="星期五" value="Friday" />
            <el-option label="星期六" value="Saturday" />
            <el-option label="星期日" value="Sunday" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="开始时间"
          prop="startTime"
          :rules="{ required: true, message: '请选择开始时间' }"
        >
          <el-time-picker
            v-model="timeSlotForm.startTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          label="结束时间"
          prop="endTime"
          :rules="{ required: true, message: '请选择结束时间' }"
        >
          <el-time-picker
            v-model="timeSlotForm.endTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="timeSlotDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTimeSlot" :loading="submittingTimeSlot"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  getTimeSlotList,
  addTimeSlot,
  publishOnlineAvailableSlots,
  type TimeSlot,
  type OnlinePublishParams,
} from '@/api/timeanlocation'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import weekOfYear from 'dayjs/plugin/weekOfYear'

dayjs.extend(weekOfYear)
dayjs.locale('zh-cn')

// 基础时间段列表
const timeSlotList = ref<TimeSlot[]>([])
const loadingTimeSlots = ref(false)

// 添加时间段对话框
const timeSlotDialogVisible = ref(false)
const timeSlotFormRef = ref<FormInstance>()
const timeSlotForm = reactive<TimeSlot>({
  dayOfWeek: '',
  startTime: '',
  endTime: '',
})
const submittingTimeSlot = ref(false)

// 发布配置相关
const publishDate = ref(dayjs().format('YYYY-MM-DD'))
const selectedSlotIds = ref<number[]>([])
const selectedSlotId = ref<number>()
const publishing = ref(false)

// 计算当前周次信息
const currentWeekInfo = computed(() => {
  if (!publishDate.value) return '请选择日期'
  const date = dayjs(publishDate.value)
  return `${date.year()}年第${date.week()}周`
})

// 可选的时间段列表（排除已选择的）
const availableSlots = computed(() => {
  return timeSlotList.value.filter((slot) => !selectedSlotIds.value.includes(slot.slotId!))
})

// 已选择的时间段详细信息
const selectedSlotsInfo = computed(() => {
  return selectedSlotIds.value.map((id) => {
    const slot = timeSlotList.value.find((s) => s.slotId === id)
    return slot || { slotId: id, dayOfWeek: '未知', startTime: '', endTime: '' }
  })
})

// 获取时间段列表
const fetchTimeSlots = async () => {
  loadingTimeSlots.value = true
  try {
    const res = await getTimeSlotList()
    if (res.code === 200 && res.data) {
      timeSlotList.value = res.data
    } else {
      ElMessage.error(res.message || '获取时间段列表失败')
    }
  } catch (error) {
    console.error('获取时间段列表失败:', error)
    ElMessage.error('获取时间段列表失败')
  } finally {
    loadingTimeSlots.value = false
  }
}

// 显示添加时间段对话框
const showAddTimeSlotDialog = () => {
  timeSlotForm.dayOfWeek = ''
  timeSlotForm.startTime = ''
  timeSlotForm.endTime = ''
  timeSlotDialogVisible.value = true
}

// 提交添加时间段
const submitTimeSlot = async () => {
  if (!timeSlotFormRef.value) return

  await timeSlotFormRef.value.validate(async (valid) => {
    if (valid) {
      submittingTimeSlot.value = true
      try {
        const res = await addTimeSlot(timeSlotForm)
        if (res.code === 200 && res.data) {
          ElMessage.success('添加时间段成功')
          timeSlotDialogVisible.value = false
          await fetchTimeSlots() // 重新加载时间段列表
        } else {
          ElMessage.error(res.message || '添加时间段失败')
        }
      } catch (error) {
        console.error('添加时间段失败:', error)
        ElMessage.error('添加时间段失败')
      } finally {
        submittingTimeSlot.value = false
      }
    }
  })
}

// 添加选中的时间段
const addSelectedSlot = () => {
  if (!selectedSlotId.value) {
    ElMessage.warning('请选择一个时间段')
    return
  }

  // 检查是否已经选择
  if (selectedSlotIds.value.includes(selectedSlotId.value)) {
    ElMessage.warning('该时间段已经选择')
    return
  }

  selectedSlotIds.value.push(selectedSlotId.value)
  selectedSlotId.value = undefined

  ElMessage.success('时间段已添加')
}

// 移除选中的时间段
const removeSelectedSlot = (index: number) => {
  selectedSlotIds.value.splice(index, 1)
}

// 发布线上配置
const publishOnlineConfig = async () => {
  if (!publishDate.value) {
    ElMessage.warning('请选择发布日期')
    return
  }

  if (selectedSlotIds.value.length === 0) {
    ElMessage.warning('请选择至少一个时间段')
    return
  }

  publishing.value = true
  try {
    const params: OnlinePublishParams = {
      publishDate: publishDate.value,
      assessmentType: '线上',
      onlineSlotIds: selectedSlotIds.value,
    }

    const res = await publishOnlineAvailableSlots(params)
    if (res.code === 200 && res.data) {
      ElMessage.success('发布线上评估时间成功')
    } else {
      ElMessage.error(res.message || '发布线上评估时间失败')
    }
  } catch (error) {
    console.error('发布线上评估时间失败:', error)
    ElMessage.error('发布线上评估时间失败')
  } finally {
    publishing.value = false
  }
}

// 处理删除时间段
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handleDeleteTimeSlot = async (row: TimeSlot) => {
  try {
    await ElMessageBox.confirm('确定要删除该时间段吗？删除后无法恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // TODO: 实现删除时间段API调用
    // 实际调用时将使用 row.slotId
    ElMessage.success('时间段删除成功')
    await fetchTimeSlots()
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
  } catch (error) {
    // 用户取消删除或删除失败
  }
}

// 转换星期英文为中文
const translateDayOfWeek = (day: string): string => {
  const dayMap: Record<string, string> = {
    Monday: '星期一',
    Tuesday: '星期二',
    Wednesday: '星期三',
    Thursday: '星期四',
    Friday: '星期五',
    Saturday: '星期六',
    Sunday: '星期日',
  }
  return dayMap[day] || day
}

onMounted(() => {
  fetchTimeSlots()
})
</script>

<style scoped>
.online-availability-container {
  padding: 20px;
}
.config-card,
.publish-card {
  margin-bottom: 20px;
}
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}
.time-slot-section {
  margin-bottom: 20px;
}
.week-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.empty-configs {
  padding: 20px 0;
}
.add-config-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}
.publish-section {
  margin-top: 20px;
  text-align: right;
}
/* 添加下拉框样式修复 */
.status-select {
  width: 256px;
}
.status-select :deep(.el-input__inner) {
  text-align: left;
}
.status-option {
  font-size: 14px;
  padding: 8px 12px;
}
</style>
